 # coding=utf-8
from django.shortcuts import *
from django.contrib.auth import authenticate, login, logout
from django.template import RequestContext, loader, Context
from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpRequest
from django.core.urlresolvers import reverse
from django.contrib.auth.forms import *

from hwcorp.apps.site.forms import *

from hwcorp.apps.site.models import *
def index(request):
    authen_form = AuthenticationForm()
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        client_ip = x_forwarded_for.split(',')[0]
    else:
        client_ip = request.META.get('REMOTE_ADDR')
        
    a = Analysis.objects.all()
    if a:
        analysis = a[0]
        last_visitor = Visitor.objects.get(order = analysis.counter)
    else:
        analysis = Analysis(counter = 0)
        analysis.save()
    if analysis.counter == 0 or last_visitor.ip != client_ip:
        analysis.counter += 1
        analysis.save()
        v = Visitor(ip = client_ip,
                    order = analysis.counter,
                    )
        v.save()
    
    v_list = Visitor.objects.all()
    import urllib
    for v in v_list:
    
        response = urllib.urlopen('http://api.ipinfodb.com/v3/ip-city/?key=0544287c2b9960f8649b986108bb447bd707eec608b53fbfcabdf89ff1be9d95&ip=' + v.ip).read()
        s = response.split(';')
        v.country_t = s[3]
        v.country = s[4]
        v.state = s[5]
        v.city = s[6]
        v.zipcode = s[7]
        v.latitude = s[8]
        v.longitude = s[9]
        v.timezone = s[10]
        
    return render_to_response('site/index.html', locals(), context_instance = RequestContext(request))

def about(request):

    return render_to_response('site/about.html', locals(), context_instance = RequestContext(request))
def contact(request):
    return render_to_response('site/contact.html', locals(), context_instance = RequestContext(request))


def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse('site_index'))
    
def login_view(request):
    if request.method == 'POST':
        user = authenticate(username = request.POST['username'], password = request.POST['password'])
        if user is not None:
            if user.is_active:
                login(request, user)
               # success
                return HttpResponseRedirect('/')
            else:
               # disabled account
               return HttpResponseRedirect(reverse('site_index'))
        else:
            # invalid login
            return HttpResponseRedirect(reverse('site_index'))
    else: 
        return render_to_response('registration/login.html', locals(), context_instance = RequestContext(request))
       
# Google Map API
#http://code.google.com/p/django-gmapi/	   
from gmapi import maps
def map(request):
    latitude = request.REQUEST.get('lat', 21.038885)
    longitude = request.REQUEST.get('lng', 105.783378)
    gmap = maps.Map(opts = {
        'center': maps.LatLng(latitude, longitude),
        'mapTypeId': maps.MapTypeId.ROADMAP,
        'zoom': 11,
        'mapTypeControlOptions': {
             'style': maps.MapTypeControlStyle.DROPDOWN_MENU
        },
    })
    marker = maps.Marker(opts = {
        'map': gmap,
        'position': maps.LatLng(latitude, longitude),
    })
    maps.event.addListener(marker, 'mouseover', 'myobj.markerOver')
    maps.event.addListener(marker, 'mouseout', 'myobj.markerOut')
    info = maps.InfoWindow({
        'content': 'You\'re Here!',
        'disableAutoPan': True
    })
    info.open(gmap, marker)
    context = {'form': MapForm(initial = {'map': gmap})}
    return render_to_response('site/map.html', context)
def demo_reponsive(request):
    return render_to_response('simple.html', locals(), context_instance = RequestContext(request))
